package cn.edu.sjtu.process_status_data.controller;

import cn.edu.sjtu.process_status_data.async.AsyncTask;
import cn.edu.sjtu.process_status_data.model.Result;
import cn.edu.sjtu.process_status_data.model.Status;
import cn.edu.sjtu.process_status_data.model.StatusMap;
import cn.edu.sjtu.process_status_data.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class DataController {
    @Autowired
    private StatusMap statusMap;
    @Autowired
    private AsyncTask task;

    @RequestMapping(value = "/data", method = RequestMethod.POST)
    public Map start(Integer num, Integer instance) {
        Map<String, Object> m = new HashMap<>();
        statusMap.statusChange(num, instance, Status.busy);
        long runTime = statusMap.getExpectedTime(num);
        task.toDone(num, instance, statusMap, runTime);
        task.toReady(num, instance, statusMap, runTime * 2);
        m.put("time", new Timestamp(System.currentTimeMillis()));
        m.put("name", statusMap.getName(num));
        m.put("message", "execute success");
        return m;
    }

    @RequestMapping(value = "/data", method = RequestMethod.GET)
    public Result getData(Integer num, Integer instance) {
        String name = statusMap.getName(num);
        Status status = statusMap.getStatus(num, instance);
        List<Object> data = statusMap.getProcessData(num, instance);
        return ResultUtil.getResult(name, status, data);
    }
}
